package org.xfy.ymcc.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.xfy.common.jwt.JwtUtils;
import org.xfy.common.jwt.PayloadData;
import org.xfy.common.jwt.RsaUtils;
import org.xfy.common.result.JsonResult;
import org.xfy.common.util.AssertUtil;
import org.xfy.ymcc.domain.Login;
import org.xfy.ymcc.dto.LoginDto;
import org.xfy.ymcc.feign.UserFeignClient;
import org.xfy.ymcc.mapper.LoginMapper;
import org.xfy.ymcc.service.ILoginService;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author xfy
 * @since 2023-11-26
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public Object accountLogin(LoginDto loginDto) {
        Login login = loginMapper.selectOne(new LambdaQueryWrapper<Login>().eq(Login::getUsername, loginDto.getUsername()));
        AssertUtil.isNotNull(login, "用户名不存在");
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(loginDto.getPassword(), login.getPassword());
        AssertUtil.isTrue(matches, "用户名或密码错误");
        login.setPassword("");
        return loginSuccess(login,loginDto.getType());
    }

    @Override
    public Object common(LoginDto loginDto) {
        Login login = loginMapper.selectOne(new LambdaQueryWrapper<Login>()
                .eq(Login::getUsername, loginDto.getUsername())
                .eq(Login::getType,loginDto.getType()));
        AssertUtil.isNotNull(login, "用户名或密码错误");
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(loginDto.getPassword(), login.getPassword());
        AssertUtil.isTrue(matches,"用户名或密码错误");
        //查询user信息
        JsonResult login1 = userFeignClient.getLogin(login.getId());
        return  loginSuccess(login1,loginDto.getType());
    }

/*    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode("123456");
        System.out.println(encode);
    }*/

    /**
     * 专门处理登录成功的业务
     *
     * @param login
     * @return
     */
    private Map<String, String> loginSuccess(Object login,Integer type) {
        Map<String, String> map = new HashMap<>();
        try {
            //1.用户类型为0的时候（后台管理系统用户），连表查询当前登录用户拥有的权限和菜单  [今天先不做]
            //2.JWT工具类生成JWT字符串  私钥加密  公钥解密
            PrivateKey privateKey = RsaUtils.getPrivateKey(FileCopyUtils.copyToByteArray(this.getClass().getClassLoader().getResourceAsStream("hrm_auth_rsa")));
            //加密得到token
            PayloadData payloadData = new PayloadData();
            //login.setPassword(null);    //置空密码，更安全
            if(type==0){ //后台用户
                payloadData.setLogin(login);
            }else {
                payloadData.setUser(login);
            }

            String token = JwtUtils.generateTokenExpireInMinutes(payloadData, privateKey, 60 * 24);  //24小时过期

            //3.封装到HashMap
            map.put("token", token);
            map.put("currentUser", JSON.toJSONString(login));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
}
